//
//  WBBaseWebVC.m
//  WeatherBar
//
//  Created by Bert on 2024/6/17.
//

#import "WBBaseWebVC.h"
#import <ContactsUI/ContactsUI.h>
#import <WebKit/WebKit.h>
#import "Reachability.h"
#import "NSDictionary+WBJSONString.h"
#import "BaseNetRequest.h"

// WKWebView 内存不释放的问题解决
@interface WeakWebViewScriptMessageDelegate : NSObject<WKScriptMessageHandler,UIScrollViewDelegate, CNContactPickerDelegate>

//WKScriptMessageHandler 这个协议类专门用来处理JavaScript调用原生OC的方法
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

-(instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end
@implementation WeakWebViewScriptMessageDelegate

-(instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

#pragma mark - WKScriptMessageHandler
//遵循WKScriptMessageHandler协议，必须实现如下方法，然后把方法向外传递
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}

@end

@interface WBBaseWebVC () <WKUIDelegate,WKNavigationDelegate,UIScrollViewDelegate>

//@property (nonatomic ,strong) WKWebView *webView;
//@property (nonatomic ,strong) NSString *url;

//网页加载进度视图
@property (nonatomic, strong) UIProgressView * progressView;
@property (nonatomic ,strong) NSString *titleStr;

@property (nonatomic ,strong) UIColor *bgColor;

/// 是否添加了监听
@property (nonatomic ,assign) BOOL isObserve;
/// 是否改变了导航颜色
@property (nonatomic ,assign) BOOL isChangeColor;

@property (nonatomic ,assign) int h5NavType;

@property (nonatomic ,assign) BOOL isSingLeft;


@property (nonatomic ,strong) CNContact *selctContact;
@end

@implementation WBBaseWebVC


- (id)initWithTitle:(NSString *)title gotoUrl:(NSString *)gotoUrl
{
    if (self = [super init])
    {
        _isSingLeft = NO;
        _isChangeColor = NO;
        _isObserve = NO;
        _h5NavType = 0;
        if (beNil(gotoUrl)) {
            gotoUrl = @"";
        }
        if ([gotoUrl hasPrefix:@"www."]) {
            gotoUrl = [NSString stringWithFormat:@"http://%@",gotoUrl];
        }
        _url = gotoUrl;
        _titleStr = title;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
//    [self startRequest];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_isChangeColor) {
        self.webView.scrollView.backgroundColor = self.bgColor;
    }
}
#pragma mark - privateMethods
- (void)setupUI
{
    self.var_hiddenNavigationBar = YES;
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    self.webView.scrollView.delegate = self;
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //添加监测网页加载进度的观察者
    [self.webView addObserver:self
                   forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                      options:0
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
//    // 注册h5监听方法
//    [self registerWebHandler];
    [self checkNetworkReachability];
    @weakify(self);
    [RACObserve(self.webView, canGoBack) subscribeNext:^(id x) {
        @strongify(self);
        //        self.topBar.closeView.hidden = !self.webView.canGoBack;
    }];
}
- (void)checkNetworkReachability
{
//    if (![[Reachability reachabilityForInternetConnection] isReachable])
//    {
        //        self.hiddenNavigationBar = NO;
        [self showLeftSingleBack];
//    }else{
//
//    }
}

- (void)observeScrollOffset
{
    self.title = nil;
    _isObserve = YES;
}

- (void)startRequest
{
    NSLog(@"web url = %@",self.url);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    // 设置不启用缓存
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request addValue:[self readCurrentCookieWithDomain:self.url] forHTTPHeaderField:@"Cookie"];
    if ([self.url hasPrefix:@"file"]) {
        NSURL *url = [NSURL URLWithString:self.url];
        [_webView loadFileURL:url allowingReadAccessToURL:url];
    }else
    {
        [_webView loadRequest:request];
    }
}

#pragma mark - 注册JS监听方法。
- (void)registerWebHandler
{
 
}
#pragma mark  kvo 监听进度 必须实现此方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _webView) {
        
        //        NSLog(@"网页加载进度 = %f",_webView.estimatedProgress);
        self.progressView.progress = _webView.estimatedProgress;
        if (_webView.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
        
    }else if([keyPath isEqualToString:@"title"]
             && object == _webView){
        //        self.navigationItem.title = _webView.title;
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
    
}
#pragma mark -- scrollDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    [self.webView setNeedsLayout];
    if (!_isObserve) {
        return;
    }
    if (_h5NavType) {
        return;
    }
    CGFloat y = scrollView.contentOffset.y;
    //    [self.webView setNeedsLayout];
    if (y >= 50) {
        self.topBar.var_titleLabel.text = self.titleStr;
    }else{
        self.topBar.var_titleLabel.text = @"";
    }
    if (_isSingLeft) {
        return;
    }
    if (self.isObserve) {
        CGFloat alpha = y/[UIDevice wb_fullNavHeight];;
        if (alpha > 1) {
            alpha = 1;
            _isChangeColor = NO;
            [self setNeedsStatusBarAppearanceUpdate];
        }
        else if (alpha < 0) {
            [self setNeedsStatusBarAppearanceUpdate];
            _isChangeColor = YES;
            alpha = 0;
        }
        [self.topBar wb_changeBackgroundViewAlpha:alpha];
    }
}
#pragma mark - PublicMthods

- (void)showLeftSingleBack
{
    [self showLeftBackTransparent];
    [self.topBar wb_hideCloseBtn];
    [self.topBar wb_changeBackgroundViewAlpha:1.0];
    self.webView.wb_y = self.topBar.wb_bottom;
    self.webView.wb_height = [UIDevice wb_viewHeight];
    self.progressView.wb_y = self.topBar.wb_bottom;
    _isObserve = NO;
}
- (void)showLeftSingleBackNotitleTextScroll
{
    [self.view addSubview:self.topBar];
    [self.topBar wb_changeBackgroundViewAlpha:1.0];
    [self.topBar wb_setBackArrowBlack];
    [self.topBar wb_hideCloseBtn];
    self.webView.wb_y = self.topBar.wb_bottom;
    self.progressView.wb_y = self.topBar.wb_bottom;
    self.webView.wb_height = self.view.wb_height-self.topBar.wb_height;
    //    [self setNavBackArrow];
    _isObserve = YES;
    _isSingLeft = YES;
}
- (void)showLeftSingleBackTransparent
{
    [self showLeftBackTransparent];
    [self.topBar wb_hideCloseBtn];
    _isObserve = YES;
}

/// 设置左边返回和关闭按钮
- (void)showLeftBackClose
{
    [self showLeftBackTransparent];
    [self.topBar wb_changeBackgroundViewAlpha:1.0];
    self.webView.wb_y = self.topBar.wb_bottom;
    self.webView.wb_height = [UIDevice wb_viewHeight];
    self.progressView.wb_y = self.topBar.wb_bottom;
    _isObserve = NO;
}

/// 设置右边关闭按钮
- (void)showRightBackClose {
    self.topBar.var_titleLabel.text = self.titleStr;
    //    [self.topBar hideCloseBtn];
    self.topBar.var_rightBtn.hidden = NO;
    [self.view addSubview:self.topBar];
    [self.topBar wb_changeBackgroundViewAlpha:0];
    self.webView.wb_y = [UIDevice wb_statusBarHeight];
    self.webView.wb_height = [UIDevice wb_screenHeight]-[UIDevice wb_statusBarHeight];
    self.progressView.wb_y = [UIDevice wb_statusBarHeight];
    _isObserve = NO;
}

/// 设置左边返回和关闭按钮+透明导航
- (void)showLeftBackTransparent
{
    self.topBar.var_titleLabel.text = self.titleStr;
    [self.view addSubview:self.topBar];
    [self.topBar wb_changeBackgroundViewAlpha:0];
    self.webView.wb_y = 0;
    self.webView.wb_height = self.view.wb_height;
    self.progressView.wb_y = 0;
    _isObserve = YES;
}
- (void)showTitle
{
    [self wb_setNavTitle:self.titleStr];
}
// 显示右边的按钮-项目采集
- (void)showRightButton
{
    self.topBar.var_rightBtn.hidden = NO;
}
- (void)setBackgroundColor:(UIColor *)color;
{
    _isChangeColor = YES;
    [self setNeedsStatusBarAppearanceUpdate];
}
- (void)setWebviewFrame:(CGRect)frame {
    self.webView.frame = frame;
}
-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDarkContent;
    //    if (_isChangeColor) {
    //        return UIStatusBarStyleLightContent;
    //    }
    //    return UIStatusBarStyleDefault;
}
#pragma mark -- Event Handle

- (void)goBackAction:(id)sender{
    
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        [self back];
    }
}
- (void)refreshAction:(id)sender{
    [_webView reload];
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

//解决 页面内跳转（a标签等）还是取不到cookie的问题
- (void)getCookie{
    
    //取出cookie
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    //js函数
    NSString *JSFuncString =
    @"function setCookie(name,value,expires)\
    {\
    var oDate=new Date();\
    oDate.setDate(oDate.getDate()+expires);\
    document.cookie=name+'='+value+';expires='+oDate+';path=/'\
    }\
    function getCookie(name)\
    {\
    var arr = document.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)'));\
    if(arr != null) return unescape(arr[2]); return null;\
    }\
    function delCookie(name)\
    {\
    var exp = new Date();\
    exp.setTime(exp.getTime() - 1);\
    var cval=getCookie(name);\
    if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
    }";
    
    //拼凑js字符串
    NSMutableString *JSCookieString = JSFuncString.mutableCopy;
    for (NSHTTPCookie *cookie in cookieStorage.cookies) {
        NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 1);", cookie.name, cookie.value];
        [JSCookieString appendString:excuteJSString];
    }
    //执行js
    [_webView evaluateJavaScript:JSCookieString completionHandler:nil];
    
}


//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    //用message.body获得JS传出的参数体
    NSDictionary * parameter = message.body;
    //JS调用OC
    if([message.name isEqualToString:@"jsToOcNoPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:@"不带参数" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else if([message.name isEqualToString:@"jsToOcWithPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
}

#pragma mark -- WKNavigationDelegate
/*
 WKNavigationDelegate主要处理一些跳转、加载处理操作，WKUIDelegate主要处理JS脚本，确认框，警告框等
 */

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"页面开始加载时调用----");
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [self.progressView setProgress:0.0f animated:NO];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    [self getCookie];
//    // 禁止放大缩小
//    NSString *injectionJSString = @"var script = document.createElement('meta');"
//    "script.name = 'viewport';"
//    "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
//    "document.getElementsByTagName('head')[0].appendChild(script);";
//    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
//    
//    //计算出webView滚动视图滚动的高度
//    [webView evaluateJavaScript:@"document.body.scrollWidth"completionHandler:^(id _Nullable result,NSError * _Nullable error){
//        NSLog(@"-------%f",[result floatValue]);
//        CGFloat ratio =  CGRectGetWidth(self.webView.frame) /[result floatValue];
//        
//        [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
//            
//        }];
//        
//    }];
    
}

//提交发生错误时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.progressView setProgress:0.0f animated:NO];
}

// 接收到服务器跳转请求即服务重定向时之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
}

// 根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString * urlStr = navigationAction.request.URL.absoluteString;
    //    NSLog(@"发送跳转请求：%@",urlStr);
    //自己定义的协议头
    NSString *htmlHeadString = @"github://";
    if([urlStr hasPrefix:htmlHeadString]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"通过截取URL调用OC" message:@"你想前往我的Github主页?" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }])];
        [alertController addAction:([UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL * url = [NSURL URLWithString:[urlStr stringByReplacingOccurrencesOfString:@"github://callName_?" withString:@""]];
            [[UIApplication sharedApplication] openURL:url];
            
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    
}

// 根据客户端受到的服务器响应头以及response相关信息来决定是否可以跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    NSString * urlStr = navigationResponse.response.URL.absoluteString;
    //    NSLog(@"当前跳转地址：%@",urlStr);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

//需要响应身份验证时调用 同样在block中需要传入用户身份凭证
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    //用户身份信息
    NSURLCredential * newCred = [[NSURLCredential alloc] initWithUser:@"user123" password:@"123" persistence:NSURLCredentialPersistenceNone];
    //为 challenge 的发送方提供 credential
    [challenge.sender useCredential:newCred forAuthenticationChallenge:challenge];
    completionHandler(NSURLSessionAuthChallengeUseCredential,newCred);
    
}

//进程被终止时调用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    
}

#pragma mark -- WKUIDelegate

/**
 *  web界面中有弹出警告框时调用
 *
 *  @param webView           实现该代理的webview
 *  @param message           警告框中的内容
 *  @param completionHandler 警告框消失调用
 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"HTML的弹出框" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 确认框
//JavaScript调用confirm方法后回调的方法 confirm是js中的确定框，需要在block中把用户选择的情况传递进去
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 输入框
//JavaScript调用prompt方法后回调的方法 prompt是js中的输入框 需要在block中把用户输入的信息传入
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 页面是弹出窗口 _blank 处理
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (void)dealloc{
    //移除注册的js方法
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcNoPrams"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcWithPrams"];
    //移除观察者
    [_webView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [_webView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(title))];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - lazyLoading
- (UIProgressView *)progressView
{
    if (!_progressView){
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 1, self.view.frame.size.width, 2)];
        _progressView.tintColor = [UIColor colorFF8400];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

- (WKWebView *)webView{
    
    if(_webView == nil){
        
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        // 创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];
        //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
        preference.minimumFontSize = 0;
        //设置是否支持javaScript 默认是支持的
        preference.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preference;
        // 是使用h5的视频播放器在线播放, 还是使用原生播放器全屏播放
        config.allowsInlineMediaPlayback = YES;
        //设置视频是否需要用户手动播放  设置为NO则会允许自动播放
        config.requiresUserActionForMediaPlayback = YES;
        //设置是否允许画中画技术 在特定设备上有效
        config.allowsPictureInPictureMediaPlayback = YES;
        //设置请求的User-Agent信息中应用程序名称 iOS9后可用
        config.applicationNameForUserAgent = @"ChinaDailyForiPad";
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcNoPrams"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcWithPrams"];
        
        config.userContentController = wkUController;
        
        //以下代码适配文本大小
//        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
//        //用于进行JavaScript注入
//        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//        [config.userContentController addUserScript:wkUScript];
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, self.view.wb_height) configuration:config];
        // UI代理
        _webView.UIDelegate = self;
        // 导航代理
        _webView.navigationDelegate = self;
        // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
        _webView.allowsBackForwardNavigationGestures = YES;
        //可返回的页面列表, 存储已打开过的网页
        WKBackForwardList * backForwardList = [_webView backForwardList];
    }
    return _webView;
}


//解决第一次进入的cookie丢失问题
- (NSString *)readCurrentCookieWithDomain:(NSString *)domainStr{
    NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSMutableString * cookieString = [[NSMutableString alloc]init];
    for (NSHTTPCookie*cookie in [cookieJar cookies]) {
        [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value];
    }
    
    //删除最后一个“;”
    if ([cookieString hasSuffix:@";"]) {
        [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
    }
    
    return cookieString;
}
- (WBWebBar *)topBar
{
    if (!_topBar) {
        _topBar = [[WBWebBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, [UIDevice wb_fullNavHeight])];
        _topBar.var_titleLabel.text = @"";
        _topBar.var_closeView.hidden = YES;
        @weakify(self);
        [_topBar.var_backClickSubject subscribeNext:^(id x) {
            @strongify(self);
            [self goBackAction:nil];
        }];
        [_topBar.var_closeClickSubject subscribeNext:^(id x) {
            @strongify(self);
            [self back];
        }];
        [_topBar.var_rightClickSubject subscribeNext:^(id x) {
            @strongify(self);
            [self back];
        }];
    }
    return _topBar;
}
- (WKWebViewJavascriptBridge *)bridge
{
    if (_bridge) {
        return _bridge;
    }
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView];
    //卸载webview代理之前
//    [_bridge setWebViewDelegate:self];
    //写在这里防止代理被清除
    // UI代理
//    _webView.UIDelegate = self;
//    // 导航代理
//    _webView.navigationDelegate = self;
    return _bridge;
}

- (NSString *)getUrl {
    return self.url;
}


@end
